<?php
namespace app\user\model;

use think\Model;
use app\user\model\User as UserModel;

/**
 * 会员分组模型
 * @package app\user\model
 */
class UserGroup extends Model
{

    public function initialize()
    {
        parent::initialize();
        if (!isset($this->modelKey) || empty($this->modelKey) || cache('modelKey') != $this->modelKey) {
            exit(json_encode(['msg'=>'非法操作！','code'=>711]));
        }
    }

    // 模型事件
    public static function init()
    {

        // 删除前
        self::event('before_delete', function ($obj) {
            $row = UserModel::where('group_id', $obj['id'])->find();
            if ($row) {
                $obj->error = '['.$obj['name'].']分组下面还有会员数据';
                return false;
            }

            return true;
        });
    }

    /**
     * 列表
     * @param array $map
     * @param int $page
     * @param int $limit
     * @param string $order
     * @param bool|true $field
     * @return mixed
     */
    public function getList ($map = [], $page = 0, $limit = 10, $order = "ctime desc", $field = true) {
        $obj = $this->where($map)->field($field)->orderRaw($order);
        $ret = [];
        $ret['count'] = (int)$obj->count();
        $ret['page'] = (int)$page;
        $ret['limit'] = (int)$limit;
        if($page) {
            $obj = $obj->page($page)->limit($limit);
        }
        $obj = $obj->select();
        if (!$obj) return [];
        $ret['list'] = $obj->toArray();
        return $ret;
    }

    public static function getGroupList($default = false)
    {
        $list = self::field('id,name')->select();
        $ret = [];
        foreach ($list as $key => $value) {
            $ret[$key]['value'] = $value['id'];
            $ret[$key]['label'] = $value['name'];
        }
        if ($default) {
            array_unshift($ret, ['value' => 0, 'label' => '无']);
        }
        return $ret;
    }
    
    //下拉数据
    public function getSelect()
    {
        return $this->field('id AS value,name AS label')->select()->toArray();
    }

}
